package com.huilian.tool.work.weixin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huilian.tool.redis.ToolRedisKey;
import com.huilian.tool.work.weixin.dto.WorkWeixinDto;
import com.huilian.tool.work.weixin.service.AuthorizeService;
import com.huilian.tool.work.weixin.service.WorkWeixinLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.Serializable;

/**
 * @author ：yjzhang
 * @date ：Created in 2023/1/10 0010 11:25
 * @description：
 * @version: 1.0
 */
@Service
@Slf4j
public class WorkWeixinLoginServiceImpl implements WorkWeixinLoginService {

    @Resource
    private AuthorizeService authorizeService;
    @Autowired
    private RedisTemplate<String, Serializable> redisCacheTemplate;

    @Override
    public JSONObject login(WorkWeixinDto workWeixinDto) throws IOException {
        String accessToken = authorizeService.getSuiteAccessToken((String) redisCacheTemplate.opsForValue().get(ToolRedisKey.WORK_WEI_XIN_SUITE_TICKET));
        //wx接口路径
        final String url = String.format("https://qyapi.weixin.qq.com/cgi-bin/service/miniprogram/jscode2session?suite_access_token=%s&js_code=%s&grant_type=authorization_code",
                accessToken, workWeixinDto.getCode());
        final CloseableHttpClient httpclient = HttpClients.createDefault();
        //使用HttpClient发送请求
        log.info(url);
        //发送Get请求
        final HttpGet httpGet = new HttpGet(url);
        final CloseableHttpResponse response = httpclient.execute(httpGet);
        final HttpEntity entity = response.getEntity();
        final JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(entity));
        log.info(jsonObject.toJSONString());
        return jsonObject;
    }

}
